import numpy as np

from classify.softmax.softmax import gradientAscent

def load_data(inputfile):
    '''

    :param inputfile:训练样本的位置
    :return: feature_data:特征
        label_data:标签
        k:类别的个数
    '''
    f = open(inputfile)
    feature_data = []
    label_data = []
    for line in f.readlines():
        feature_tmp = []
        feature_tmp.append(1)
        lines = line.strip().split("\t")
        for i in range(len(lines) - 1):
            feature_tmp.append(float(lines[i]))
        label_data.append(int(lines[-1]))

        feature_data.append(feature_tmp)
    f.close()
    return np.mat(feature_data), np.mat(label_data).T, len(set(label_data))

def save_model(file_name, weights):
    '''
    保存最终的模型
    :param file_name:保存的文件名
    :param weights: softmax模型
    '''
    f_w = open(file_name, "w")
    m, n = np.shape(weights)
    for i in range(m):
        w_tmp = []
        for j in range(n):
            w_tmp.append(str(weights[i, j]))
        f_w.write("\t".join(w_tmp) + "\n")
    f_w.close()

if __name__ == "__main__":
    pwd = "/home/xiefeihong/PycharmProjects/SimpleMachineLearning/static/classify/softmax/"
    inputfile = pwd + "train_data.txt"

    print("---- 1.load data")
    feature, label, k = load_data(inputfile)

    print("---- 2.training")
    weights = gradientAscent(feature, label, k, 10000, 0.4)

    print("---- 3.save model")
    save_model("weights", weights)